package com.mediacloud.app.newsmodule.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.baidu.location.BDLocation;
import com.mediacloud.app.appfactory.cache.AppConfig;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.activity.BaseBackActivity4NoDetail;
import com.mediacloud.app.model.interfaces.ILocation;
import com.mediacloud.app.model.interfaces.IPermissionsAgree;
import com.mediacloud.app.model.interfaces.PermissionUtil;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.lbs.LBSCityItemHolder;
import com.mediacloud.app.newsmodule.adaptor.lbs.LBSCityListAdaptor;
import com.mediacloud.app.newsmodule.adaptor.lbs.LBSGroupTitleHolder;
import com.mediacloud.app.newsmodule.utils.LBSChooseListener;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.enums.XKey;
import com.mediacloud.app.reslib.model.LBSItem;
import com.mediacloud.app.reslib.util.LBSUtils;
import com.tencent.mmkv.MMKV;

import java.util.List;


/**
 * lbs城市列表
 */
public class LBSCityListChooseActivity extends BaseBackActivity4NoDetail implements AdapterView.OnItemClickListener, View.OnClickListener {
    LBSGroupTitleHolder currentLocationGroupTitleHolder;
    LBSCityItemHolder currentLocationCityTitleHolder;
    LBSGroupTitleHolder otherCityListTitleHolder;
    ListView lbsCityList;
    LBSCityListAdaptor adaptor;
    //把栏目id传过来 只要要取里面的列表和lbs显示的行政级别
    CatalogItem catalogItem;
    public int choosedIndex = -1;

    int lastIndex = -1;
    /**
     * 记录刚进来时候的id  结束的时候作对比 用来判断是否是选择的非同一个 不是同一个就刷新
     */
    String lastId;
    /**
     * 默认没有选取过地区或是选取 过的地区与现有地区匹配不上来的情况 的
     */
    LBSItem defaultNone;
    List<LBSItem> lbsItems;
    LBSItem lastChoosedItem;
    String lastChoosedItemCity_nid;
    //当前页面打开后操作后选择的
    LBSItem currentActionChoosed;
    ImageView gpsSwitch;
    //   Handler checkHandler;
    AppConfig appConfig;
    View gps_layout;

    @Override
    public int getLayoutResID() {
        return R.layout.aappfactory_activity_lbslocation_choosestate;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        invokeLocation();
    }

    private void invokeLocation() {
        if (appConfig.lbsIsAutoMode()) {
            PermissionUtil.INSTANCE.invokeLocationPermission(this, new IPermissionsAgree() {
                @Override
                public void onAgree() {
                    PermissionUtil.INSTANCE.getLocation(LBSCityListChooseActivity.this, new ILocation() {
                        @Override
                        public void onLocation(@NonNull BDLocation location) {
                            showLocationHeaderTitle();
                        }

                        @Override
                        public void onFail() {

                        }
                    });
                }

                @Override
                public void onRefuse() {

                }

                @Override
                public void hasPermissions() {

                }
            });
        }
    }

    private void initView() {
        appConfig = new AppConfig(this);
        LBSChooseListener.getInstance().hadHandle = false;
        catalogItem = getIntent().getParcelableExtra("data");
        lastId = catalogItem.getCatid();
        currentLocationGroupTitleHolder = new LBSGroupTitleHolder(findViewById(R.id.currentLocationGroupTitle));
        currentLocationCityTitleHolder = new LBSCityItemHolder(findViewById(R.id.currentLocationCityTitle));
        otherCityListTitleHolder = new LBSGroupTitleHolder(findViewById(R.id.otherCityListTitle));
        lbsCityList = Utility.findViewById(getWindow(), R.id.lbsCityList);
        gps_layout = Utility.findViewById(getWindow(), R.id.gps_layout);
        currentLocationGroupTitleHolder.locationGroupTitle.setText(R.string.lbscurrentlocation_title);
        adaptor = new LBSCityListAdaptor(this);
        //先看上次有无选择的
        lastChoosedItem = LBSUtils.getChoosedLBSItemData(this, catalogItem.getLbsItem().getNavigateId());
        lbsItems = catalogItem.getLbsItemList();
        defaultNone = catalogItem.getLbsItemList().get(0);
        setDefaultChoosed();
        setChoosedTitles();
        showLocationHeaderTitle();
        adaptor.lastChooseItem = lastChoosedItem;
        for (int i = 0; lastChoosedItem != null && i < lbsItems.size(); i++) {
            LBSItem lbsItem = lbsItems.get(i);
            if (lbsItem.getCity_name().equals(lastChoosedItem.getCity_name())) {
                lastIndex = i;
                //记录上次选择的citynid 再看结束时候两个id是否一样  如果一样就不刷新 只更新标签名
                lastChoosedItemCity_nid = lastChoosedItem.getCity_nid();
                break;
            }
        }
        adaptor.setListContentData(lbsItems);

        if (lastIndex == -1)
            lastIndex = 0;
        lbsCityList.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!isFinish)
                    lbsCityList.smoothScrollToPosition(lastIndex);
            }
        }, 350);
        lbsCityList.setAdapter(adaptor);
        lbsCityList.setOnItemClickListener(this);

        otherCityListTitleHolder.locationGroupTitle.setText(R.string.lbschooseotherlocation);
        gpsSwitch = Utility.findViewById(mRootView, R.id.gpsSwitch);
        gpsSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                appConfig.setLbsIsAutoMode(!appConfig.lbsIsAutoMode());
                updateGPSImage();
                invokeLocation();
            }
        });
        updateGPSImage();

        gps_layout.setVisibility(View.VISIBLE);
    }

    private void updateGPSImage() {
        if (appConfig.lbsIsAutoMode()) {
            gpsSwitch.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.gps_open));
        } else {
            gpsSwitch.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.gps_close));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (MMKV.defaultMMKV().getBoolean(XKey.REFRESH_LOCATION, false)) {
            MMKV.defaultMMKV().putBoolean(XKey.REFRESH_LOCATION, false);
            PermissionUtil.INSTANCE.getLocation(LBSCityListChooseActivity.this, new ILocation() {
                @Override
                public void onLocation(@NonNull BDLocation location) {
                    showLocationHeaderTitle();
                }

                @Override
                public void onFail() {

                }
            });
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //   checkHandler.removeMessages(0);
    }

    protected void getGPSStatus() {
        //  gps_layout.setVisibility(Utility.gpsIsOpen(this) ? View.VISIBLE : View.GONE);
        gps_layout.setVisibility(View.VISIBLE);
    }


    protected void setDefaultChoosed() {
        if (lastChoosedItem == null) {
            if (AppFactoryGlobalConfig.getAddress() != null) {
                String cityName = LBSItem.getLBSCityName(AppFactoryGlobalConfig.getAddress(), catalogItem.getLbs_ide());
                LBSItem matched = LBSItem.matchCityFromList(lbsItems, cityName);//匹配定位与列表中有无相关城市
                if (matched != null)//有则用匹配到的那个
                {
                    lastChoosedItem = matched;
                } else//没得 就用默认
                {
                    lastChoosedItem = defaultNone;
                }
            } else//没得 就用默认
            {
                lastChoosedItem = defaultNone;
            }
        } else//如果有上次选择过的 那再看列表里面有无选择过的  有就得到这个选择过的 没得 就用默认的了
        {
            LBSItem matched = LBSItem.matchCityFromList(lbsItems, lastChoosedItem.getCity_name());
            if (matched == null) {
                lastChoosedItem = defaultNone;
            } else {
                lastChoosedItem = matched;
            }
        }
    }

    protected void setChoosedTitles() {
        String current_location_navigate_title = getResources().getString(R.string.current_location_navigate_title);

        //第一次进来 肯定是没得选择过的
        if (lastChoosedItem == null) {
            //没选择那先看定位sdk定位成功没 定位成功了就匹配一下咯
            //如果匹配成功了的 那就用匹配了的那个
            if (AppFactoryGlobalConfig.getAddress() != null) {
                String cityName = LBSItem.getLBSCityName(AppFactoryGlobalConfig.getAddress(), catalogItem.getLbs_ide());
                LBSItem matched = LBSItem.matchCityFromList(lbsItems, cityName);//匹配定位与列表中有无相关城市
                if (matched != null)//有则用匹配到的那个
                {
                    current_location_navigate_title = current_location_navigate_title.concat(matched.getName());
                } else//没得 就用默认
                {
                    current_location_navigate_title = current_location_navigate_title.concat(defaultNone.getName());
                }
            } else//没得 就用默认
            {
                current_location_navigate_title = current_location_navigate_title.concat(defaultNone.getName());
            }
        } else//如果有上次选择过的 那再看列表里面有无选择过的  有就得到这个选择过的 没得 就用默认的了
        {
            LBSItem matched = LBSItem.matchCityFromList(lbsItems, lastChoosedItem.getCity_name());
            if (matched == null) {
                current_location_navigate_title += defaultNone.getName();
            } else {
                current_location_navigate_title += matched.getName();
            }
        }
        setTitle(current_location_navigate_title);
    }


    protected void showLocationHeaderTitle() {
        if (AppFactoryGlobalConfig.getAddress() != null) {
            String cityName = LBSItem.getLBSCityName(AppFactoryGlobalConfig.getAddress(), catalogItem.getLbs_ide());
            currentLocationCityTitleHolder.rootView.setOnClickListener(this);
            currentLocationCityTitleHolder.showLocationAddrss(cityName);
        } else
            currentLocationCityTitleHolder.noneLocation().setOnClickListener(v -> PermissionUtil.INSTANCE.invokeLocationPermission(LBSCityListChooseActivity.this, new IPermissionsAgree() {
                @Override
                public void onRefuse() {

                }

                @Override
                public void hasPermissions() {
                    onAgree();
                }

                @Override
                public void onAgree() {
                    PermissionUtil.INSTANCE.getLocation(LBSCityListChooseActivity.this, new ILocation() {
                        @Override
                        public void onLocation( BDLocation location) {
                            showLocationHeaderTitle();
                        }

                        @Override
                        public void onFail() {

                        }
                    });
                }
            }));
    }


    @Override
    public void onClick(View v) {
        /**
         LBSItem tempLastChoosed= LBSUtils.getChoosedLBSItemData(this,catalogItem.getLbsItem().getNavigateId());
         if(tempLastChoosed!=null)
         {
         LBSUtils.deleteChoosedLBSItemData(this,tempLastChoosed.getNavigateId());
         }
         adaptor.lastChooseItem=null;
         final String cityName=LBSItem.getLBSCityName(AppFactoryGlobalConfig.locationAddress,catalogItem.getLbs_ide());
         //先看当前定位城市有无匹配
         LBSItem matched=LBSItem.matchCityFromList(lbsItems,cityName);
         if(matched!=null)//有匹配那就优先显示匹配上的
         {
         currentActionChoosed=matched;
         }
         updatedChoosedLocation();
         if(matched!=null&&currentActionChoosed!=null)
         {
         LBSUtils.deleteChoosedLBSItemData(this,currentActionChoosed.getNavigateId());
         }
         ***/
        finish();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        position = position - lbsCityList.getHeaderViewsCount();
        choosedIndex = position;
        LBSItem item = adaptor.getItem(choosedIndex);
        currentActionChoosed = item;
        if (lastIndex != choosedIndex) {
            updatedChoosedLocation();
        }
        finish();
    }

    protected void updatedChoosedLocation() {
        if (currentActionChoosed == null)
            return;
        if (lastChoosedItem != null) {
            LBSUtils.deleteChoosedLBSItemData(this, lastChoosedItem.getNavigateId());
        }
        boolean equals = currentActionChoosed.getCity_nid().equals(lastChoosedItemCity_nid);
        //如果是切换了选择城市的
        catalogItem.setLbsItem(currentActionChoosed);
        catalogItem.setCatalog_type(currentActionChoosed.getCategory());
        catalogItem.setCatalogStyle(currentActionChoosed.getStyle());
//        catalogItem.setCatid(currentActionChoosed.getCity_nid());
        //用他来取数据
        catalogItem.setLbsNavigateDataId(currentActionChoosed.getCity_nid());
        catalogItem.setCatname(currentActionChoosed.getName());
        catalogItem.setStyleOther(currentActionChoosed.getStyle_other());
        catalogItem.setAfpAdCatalog(currentActionChoosed.getAd());
        adaptor.lastChooseItem = currentActionChoosed;
        LBSUtils.addOrUpdateChoosedLBSItemData(this, currentActionChoosed);
        getIntent().putExtra("sameId", equals);
        getIntent().putExtra("catalog", catalogItem);
        setResult(RESULT_OK, getIntent());
    }

    @Override
    public void finish() {
        //   checkHandler.removeMessages(0);
        super.finish();
    }
}